import http from "@/utils/http";
import { defineStore } from "pinia";

export interface IUserState {
    username: string;
    token: string;
}

export const userModule = defineStore('USER', {
    persist: true, // 持久化
    state(): IUserState { 
        return {
            username: '',
            token: ''
        }
    },

    actions: {
        async login(loginUser: { username: string; password: string; }) {
            const response = await http.post({
                url: 'api/login',
                duplicateRequestValidation: true,
                duplicateRequestValidationTime: 2000,
                data: loginUser
            })
            if (response.code === 200) {
                this.username = response.data.username;
                this.token = response.data.token;
            }
        },

        async logout() {
            const response = await http.post({
                url: 'logout',
                data: {'username': this.username}
            })
            if (response.code === 200) {
                this.username = '';
                this.token = '';
            }
        }
    }
})